package cn.openea.perpartner.meily.web.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.core.exception.ServiceException;
import cn.openea.perpartner.common.core.utils.Arith;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.meily.behavioral.entity.BehavioralData;
import cn.openea.perpartner.meily.behavioral.service.IBehavioralDataService;
import cn.openea.perpartner.meily.util.UserContext;
import cn.openea.perpartner.meily.web.entity.LearningCourse;
import cn.openea.perpartner.meily.web.entity.vo.CourseSeSearchVo;
import cn.openea.perpartner.meily.web.entity.vo.CourseVo;
import cn.openea.perpartner.meily.web.mapper.LearningCourseMapper;
import cn.openea.perpartner.meily.web.service.ILearningCourseService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.NonNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;


@Service("learningCourseService")
public class LearningCourseServiceImpl extends ServiceImpl<LearningCourseMapper, LearningCourse> implements ILearningCourseService {

    @Resource
    private IBehavioralDataService behavioralDataService;

    @Override
    public List<LearningCourse> selectList(CourseSeSearchVo searchVo) {
        return baseMapper.selectList(buildQueryWrapper(searchVo, true));
    }

    private LambdaQueryWrapper<LearningCourse> buildQueryWrapper(CourseSeSearchVo searchVo, boolean isSort) {
        if (null == searchVo) {
            return null;
        }
        searchVo.buildDateRangeParams();
        LambdaQueryWrapper<LearningCourse> queryWrapper = new LambdaQueryWrapper<>();
        if (searchVo.getStatus() != null) {
            queryWrapper.eq(LearningCourse::getStatus, searchVo.getStatus());
        }
        if (searchVo.getType() != null) {
            queryWrapper.eq(LearningCourse::getType, searchVo.getType());
        }
        if (StringUtils.isNotBlank(searchVo.getCategory())) {
            queryWrapper.likeRight(LearningCourse::getCategory, searchVo.getCategory());
        }
        if (StringUtils.isNotBlank(searchVo.getId())) {
            queryWrapper.like(LearningCourse::getId, searchVo.getId());
        }
        if (StringUtils.isNotBlank(searchVo.getTitle())) {
            queryWrapper.like(LearningCourse::getTitle, searchVo.getTitle());
        }

        String searchStr = searchVo.getSearchStr();
        if (StringUtils.isNotBlank(searchStr)) {
            queryWrapper.and(wrap -> wrap.like(LearningCourse::getTitle, searchStr)
                    .or().like(LearningCourse::getEnterpriseName, searchStr)
                    .or().like(LearningCourse::getCategory, searchStr)
                    .or().like(LearningCourse::getTags, searchStr));
        }
        if (StringUtils.isNotBlank(searchVo.getStartDate()) && StringUtils.isNotBlank(searchVo.getEndDate())) {
            queryWrapper.apply("DATE(create_time) BETWEEN '" + searchVo.getStartDate() + "' AND '" + searchVo.getEndDate() + "'");
        }
        if (isSort) {
            queryWrapper.orderByDesc(LearningCourse::getTop);
            queryWrapper.orderByDesc(LearningCourse::getCreateTime);
        }
        return queryWrapper;
    }

    @Override
    public boolean shelfCourse(@NonNull Long id) {

        /**
         * 2023-07-05 add by lys 汇集数据
         * 用于企业动态的展示（暂时不需要管数据是否插入成功）
         */
        /*发布学习
        文案：我刚上传了一个学习资源，快来一起充充电吧。*/
        LearningCourse course = getById(id);
        if(BeanUtil.isNotEmpty(course)){
            BehavioralData behavioralData = new BehavioralData();
            behavioralData.setTitle("我刚上传了一个学习资源，快来一起充充电吧。");// 文案
            behavioralData.setSubject(course.getTitle());// 标题
            behavioralData.setContent(course.getDescription());// 内容（课程描述）
            behavioralData.setImage(course.getMainDiagram());// 图片
            behavioralData.setPrice(course.getPrice().toString());
            behavioralData.setLabel(course.getTags());
            behavioralData.setType("0");// 类型。0动态；1工作；2商品；3创作
            behavioralData.setJumpUrl("pages_private_scene1/CourseZone/CourseDetail?id=" + course.getId());// 课程详情页面
            behavioralData.setSourceId(String.valueOf(course.getId()));// 来源id
            behavioralData.setSourceType("6");// 来源类型。0团购；1测评；2样品；3招聘；4协作；5上架商品；6发布学习
            behavioralData.setUserId(course.getCreateUser());
            behavioralData.setUserName("");
            behavioralData.setStatus("1");// 状态。0停用；1启用
            behavioralData.setEnterpriseNo(course.getEnterpriseNo());// 企业编号
            behavioralData.setEnterpriseName(course.getEnterpriseName());// 企业名称
            behavioralData.setCreateTime(DateUtil.now());
            behavioralData.setUpdateTime(DateUtil.now());
            behavioralDataService.save(behavioralData);
        }

        Optional.ofNullable(getById(id))
                .orElseThrow(() -> new ServiceException("课程不存在"));
        return updateById(LearningCourse.builder()
                .id(id)
                .status((short) 0).build());
    }

    @Override
    public boolean downCourse(@NonNull Long id) {
        Optional.ofNullable(getById(id))
                .orElseThrow(() -> new ServiceException("课程不存在"));
        return updateById(LearningCourse.builder()
                .id(id)
                .status((short) 1).build());
    }

    @Override
    public boolean topCourse(@NonNull Long id) {
        Optional.ofNullable(getById(id))
                .orElseThrow(() -> new ServiceException("课程不存在"));
        // 查询最上面的一个数据
        LearningCourse course = getOne(Wrappers.<LearningCourse>lambdaQuery()
                .orderByDesc(LearningCourse::getTop)
                .last("limit 1"));
        int top = 1;
        if (BeanUtil.isNotEmpty(course)) {
            top = Convert.toInt(Arith.add(course.getTop(), 1));
        }
        return updateById(LearningCourse.builder()
                .id(id)
                .top(top).build());
    }

    @Override
    public boolean cancelTopCourse(@NonNull Long id) {
        LearningCourse oldCourse = Optional.ofNullable(getById(id))
                .orElseThrow(() -> new ServiceException("资源不存在"));
        if (oldCourse.getTop() == 0) {
            // 不用继续下去了，本来就没有置顶
            return true;
        }
        LearningCourse course = getOne(Wrappers.<LearningCourse>lambdaQuery()
                .orderByDesc(LearningCourse::getTop)
                .last("limit 1"));
        if (!course.getId().equals(id)) {
            // 这个视频置顶优先级高的进行降级 比如 这个视频排序5，现在要取消置顶，就要有视频取代它的位置
            baseMapper.downgradeTop(oldCourse.getTop());
        }
        return updateById(LearningCourse.builder()
                .id(id)
                .top(0).build());
    }

    @Override
    public void addCourse(CourseVo courseVo) {
        LearningCourse course = new LearningCourse();
        BeanUtil.copyProperties(courseVo, course);
        course.setStatus((short) 0);
        course.setCreateUser(UserContext.getUserId());
        baseMapper.insert(course);
    }

    @Override
    public void editCourse(CourseVo courseVo) {
        Optional.ofNullable(getById(courseVo.getId()))
                .orElseThrow(() -> new ServiceException("课程资源不存在"));
        LearningCourse course = new LearningCourse();
        BeanUtil.copyProperties(courseVo, course);
        course.setCreateUser(UserContext.getUserId());
        baseMapper.updateById(course);
    }
}